package com.example.jdbcdemo;

import java.sql.*;
import java.time.LocalDate;
import java.util.Random;

public class JDBCMoreInsert {
    public static void main(String[] args){
        String url = "jdbc:mysql://localhost:3306/jdbc_demo?serverTimezone=GMT&characterEncoding=UTF-8";
        String user = "root";
        String password = "123456";
        // 批量插入数据
        String sql = "INSERT INTO teacher(id, name, course, birthday) VALUES(?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(url, user, password);) {
            conn.setAutoCommit(false);
            try (PreparedStatement ps = conn.prepareStatement(sql);) {
                Random random = new Random();
                // 设置参数
                for (int i = 0; i < 500; i++) {
                    // 随机生成年份，假设在2000年到2023年之间
                    int year = 2000 + random.nextInt(24);
                    // 随机生成月份，假设在1月到12月之间
                    int month = random.nextInt(12) + 1;
                    // 随机生成日期，假设在1日到28日之间
                    int dayOfMonth = random.nextInt(28) + 1;
                    // 创建日期对象
                    LocalDate birthday = LocalDate.of(year, month, dayOfMonth);
                    // 将日期转换为字符串
                    String dateString = birthday.toString();

                    ps.setInt(1, i + 1);
                    ps.setString(2, "name" + i);
                    ps.setString(3, "course" + i);
                    ps.setDate(4, Date.valueOf(dateString));
                    // 添加到批处理
                    ps.addBatch();
                    if (i % 100 == 0) { // 每5条记录执行一次批处理
                        ps.executeBatch();
                        ps.clearBatch();
                    }
                }
                ps.executeBatch();
                conn.commit();
                System.out.println("完成批量插入数据");
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
